<?php

namespace app\index\controller;

use app\baidu\model\AdminSetting;

use app\farm\model\User;
use app\massage\model\CouponAtv;
use app\redbag\model\Invitation;
use app\restaurant\model\ClassDate;
use Exception;
use longbingcore\tools\LongbingDefault;
use think\App;
use think\facade\Db;
use think\Response;
use app\baidu\model\AdminActive;

class Login
{
    //  小程序登陆每个用户产生的唯一表示
    protected $code = '';

    protected $uniacid;
    protected $request;
    protected $_param;
    protected $_input;

    function __construct(App $app)
    {
        global $_GPC, $_W;

        $this->request = $app->request;
        //获取param
        $this->_param = $this->request->param();

        $this->_input = json_decode($this->request->getInput(), true);
        //获取uniacid
        if (!isset($this->_param['i']) || !$this->_param['i']) {

            return $this->error('need uniacid',400);
        }

        $this->uniacid = $this->_param['i'];
    }

    /**
     * @author chenniang
     * @DataTime: 2021-03-17 10:06
     * @功能说明:小程序用户登陆接口
     */
    function index()
    {
        $input = $this->_param;

        if (!isset($this->_param['code']) || !$this->_param['code']) {

            return $this->error(['code' => 400, 'error' => 'need code']);

        }

        $cap_id = !empty($input['cap_id'])?$input['cap_id']:0;

        $code    = $this->_param['code'];
        //  是否是微擎
        $config = longbingGetAppConfig($this->uniacid);

        $appid  = $config['appid'];

        $appsecret = $config['appsecret'];
        //  从微信获取openid等
        $url  = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appsecret}&js_code={$code}&grant_type=authorization_code";

        $arrContextOptions = array(

            "ssl"=>array(

                "verify_peer"     => false,

                "verify_peer_name"=> false,
            ),
        );

        $info = file_get_contents($url ,false, stream_context_create($arrContextOptions));

        $info = @json_decode($info, true);
        //  微信端返回错误
        if (isset($info['errcode'])) {

            return $this->error($info['errcode'] . ', errmsg: ' . $info['errmsg']);

        }
        if (!isset($info['session_key'])) {

            return $this->error('session_key not exists','402');

        }

        if(empty($info['openid'])){

            return $this->error('openid not exists');

        }

        $user_model = new User();

        $dis = [

            'openid'  => $info['openid'],

            'uniacid' => $this->uniacid

        ];

        $user_info = $user_model->dataInfo($dis);

        if(empty($user_info)){

            try {

                $insert = [

                    'uniacid' => $this->uniacid,

                    'openid' => $info['openid'],

                    'cap_id' => $cap_id,

                    'session_key' => $info['session_key'],


                ];

                if(!empty($input['pid'])){

                    $insert['pid'] = $input['pid'];
                }

                $user_model->dataAdd($insert);

            }catch(Exception $e)
            {}

           // $user_id = $user_model->getLastInsID();

            $user_info = $user_model->dataInfo($insert);


        }else{

            $user_model->dataUpdate(['id'=>$user_info['id']],['session_key'=>$info['session_key']]);
        }

        $key = 'longbing_user_autograph_' . $user_info['id'];

        $key = md5($key);

        setCache($key, $user_info, 7200, $this->uniacid);

        $arr = [

            'data'      => $user_info,

            'autograph' => $key
        ];

        return $this->success($arr);

    }

    //返回成功
    public function success($data, $code = 200)
    {
        $result['data'] = $data;
        $result['code'] = $code;
        $result['sign'] = null;

        return $this->response($result, 'json', $code);
    }

    //返回错误数据
    public function error($msg, $code = 400)
    {
        $result['error'] = $msg;
        $result['code'] = $code;
        return $this->response($result, 'json', $code);
    }

    //response
    protected function response($data, $type = 'json', $code = 200)
    {
        return Response::create($data, $type)->code($code);
    }



    /**
     * @author chenniang
     * @DataTime: 2021-03-17 10:06
     * @功能说明:微信登陆
     */
    function appLogin()
    {
        $input = $this->_input;

        $uniacid = $this->uniacid;

        $input = $input['data'];

        $cap_id = !empty($input['cap_id'])?$input['cap_id']:0;

        $user_model = new User();

        $dis = [

            'unionid'  => $input['unionId'],

        ];

        $user_info = $user_model->dataInfo($dis);

        $insert = [

            'uniacid'  => $uniacid,

            'nickName' => $input['nickName'],

            'avatarUrl'=> $input['avatarUrl'],

            'unionid'  => $input['unionId'],

            'gender'   => $input['gender'],

            'city'     => $input['city'],

            'province' => $input['province'],

            'country'  => $input['country'],

            'openid'   => $input['openId'],

            'app_openid' => $input['openId'],

            'push_id'    => !empty($input['push_id'])?$input['push_id']:'',

            'cap_id'     => $cap_id,

            'last_login_type' => 1,

        ];

        if(empty($user_info)){

            if(!empty($input['pid'])){

                $insert['pid'] = $input['pid'];
            }

            $user_model->dataAdd($insert);

            $user_id  = $user_model->getLastInsID();

        }else{

            $user_id = $user_info['id'];

            $user_model->dataUpdate(['id'=>$user_id],$insert);

        }

        $user_info = $user_model->dataInfo(['id'=>$user_id]);

        $key = 'longbing_user_autograph_' . $user_info['id'];

        $key = md5($key);

        setCache($key, $user_info, 7200, $this->uniacid);

        $arr = [

            'data'      => $user_info,

            'autograph' => $key
        ];

        return $this->success($arr);

    }



    /**
     * @author chenniang
     * @DataTime: 2021-03-17 10:06
     * @功能说明:ios登陆
     */
    function iosLogin()
    {
        $input = $this->_input;

        $uniacid = $this->uniacid;

        $input = $input['data'];

        $cap_id = !empty($input['cap_id'])?$input['cap_id']:0;

        $user_model = new User();

        $dis = [

            'openid'  => $input['openId'],

        ];

        $user_info = $user_model->dataInfo($dis);

        $familyName = !empty($input['fullName']['familyName'])?$input['fullName']['familyName']:'';

        $giveName   = !empty($input['fullName']['giveName'])?$input['fullName']['giveName']:'';

        $name = !empty($familyName.$giveName)?$familyName.$giveName:'默认用户';

        $insert = [

            'uniacid'  => $uniacid,

            'nickName' => $name,

            'avatarUrl'=> 'https://lbqny.migugu.com/admin/farm/default-user.png',

//            'unionid'  => $input['unionId'],
//
//            'gender'   => $input['gender'],
//
//            'city'     => $input['city'],
//
//            'province' => $input['province'],
//
//            'country'  => $input['country'],

            'openid'   => $input['openId'],

            //'app_openid' => $input['openId'],

            'push_id'    => !empty($input['push_id'])?$input['push_id']:'',

            'cap_id'     => $cap_id,

            'last_login_type' => 1,

        ];

        if(empty($user_info)){

            if(!empty($input['pid'])){

                $insert['pid'] = $input['pid'];
            }

            $user_model->dataAdd($insert);

            $user_id  = $user_model->getLastInsID();

        }else{

            $user_id = $user_info['id'];

            $user_model->dataUpdate(['id'=>$user_id],$insert);

        }

        $user_info = $user_model->dataInfo(['id'=>$user_id]);

        $key = 'longbing_user_autograph_' . $user_info['id'];

        $key = md5($key);

        setCache($key, $user_info, 7200, $this->uniacid);

        $arr = [

            'data'      => $user_info,

            'autograph' => $key
        ];

        return $this->success($arr);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-10 18:30
     * @功能说明:
     */
    public function getConfig(){

        $config    = longbingGetAppConfig($this->uniacid);

        $data['login_protocol'] = $config['login_protocol'];

        $data['app_text'] = $config['app_text'];

        $data['app_logo'] = $config['app_logo'];

        $data['ios_login'] = $config['ios_login'];

        $data['information_protection'] = $config['information_protection'];

        $data['app_banner'] = $config['app_banner'];

        return $this->success($data);

    }





}
